//
//  ViewController.swift
//  MacStudy
//
//  Created by 30san on 2020/9/18.
//  Copyright © 2020 Dawninest. All rights reserved.
//

import Cocoa

class ViewController: NSViewController {
    
    @IBOutlet weak var collectionView: NSCollectionView!
    
    private let itemID = "MainCollectionViewItem"
    private let dataSources = [
        "NSTextField",
        "NSButton",
        "NSSegmentedControl",
        "NSComboBox",
        "NSTableView",
        "Other",
        "CollectionView",
        "Tab",
        "SplitView",
        "Popover",
        "Menu",
        "Outline",
        "Notification"
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let flowLayout = NSCollectionViewFlowLayout()
        flowLayout.itemSize = NSMakeSize(100, 100)
        flowLayout.minimumLineSpacing = 20
        flowLayout.minimumInteritemSpacing = 20
        self.collectionView.collectionViewLayout = flowLayout
        collectionView.register(MainCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier.init(itemID))
        collectionView.delegate = self
        collectionView.dataSource = self
        view.wantsLayer = true
    }
    
    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}

extension ViewController: NSCollectionViewDelegate {
    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
        print("collectionView = \(indexPaths)")
        guard let item = indexPaths.first?.item else {
            return
        }
        let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
        // NSTextFieldViewController
        let sceneIdentifier = "\(dataSources[item])ViewController"
        print("sceneIdentifier = \(sceneIdentifier)")
        let vc = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier.init(sceneIdentifier)) as! NSViewController
        // 弹出新窗口
        presentAsModalWindow(vc)
        // 向下弹出模板窗口
//        presentAsSheet(vc)
        // NSPopover 弹出方式
        // 转场动画
    }
}

extension ViewController: NSCollectionViewDataSource {
    func numberOfSections(in collectionView: NSCollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSources.count
    }
    
    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        let cell = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: itemID), for: indexPath) as! MainCollectionViewItem
        cell.contentLabel.stringValue = "\(dataSources[indexPath.item])"
        return cell
    }
}
